package com.shopping.mall.core.module.saleData.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping.mall.base.util.DateUtils;
import com.shopping.mall.core.module.cart.entity.Cart;
import com.shopping.mall.core.module.goodData.service.GoodDataService;
import com.shopping.mall.core.module.ipAddress.entity.IpAddress;
import com.shopping.mall.core.module.order.entity.Order;
import com.shopping.mall.core.module.saleData.entity.SaleData;
import com.shopping.mall.core.module.saleData.entity.SaleDataQueryVO;
import com.shopping.mall.core.module.saleData.mapper.SaleDataMapper;
import com.shopping.mall.core.module.saleData.service.SaleDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopping.mall.base.http.ResponseState;
import com.shopping.mall.base.http.Result;
import com.shopping.mall.base.util.WrapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.List;
/**
 * <p>
 *  SaleData服务实现类
 * </p>
 *
 * @author zzy
 * @since 2021-09-01
 */
@Validated
@Service
public class SaleDataServiceImpl extends ServiceImpl<SaleDataMapper, SaleData> implements SaleDataService {

    @Autowired
    private SaleDataMapper saleDataMapper;

    @Autowired
    private GoodDataService goodDataService;

    /**
     * 分页查询
     * @param current ：页码
     * @param size ：每页条数
     * @param saleDataQueryVO ：筛选条件
     * @return IPage<SaleData>
     */
    @Override
    public IPage<SaleData> getSaleDataPage(Integer current, Integer size, SaleDataQueryVO saleDataQueryVO){
        QueryWrapper<SaleData> queryWrapper = WrapperUtils.queryWrapperByQueryVONoTime(saleDataQueryVO);
        if(saleDataQueryVO.getBefore()!=null){
            queryWrapper.ge("date",saleDataQueryVO.getBefore());
        }
        if(saleDataQueryVO.getAfter()!=null){
            queryWrapper.le("date",saleDataQueryVO.getAfter());
        }
        queryWrapper.orderByDesc("date");
        Page<SaleData> saleDataPage = new Page<>(current,size);
        IPage<SaleData> saleDataIPage = saleDataMapper.selectPage(saleDataPage, queryWrapper);
        return saleDataIPage;
    }

    /**
     * 查询所有
     * @param saleDataQueryVO ：筛选条件
     * @return List<SaleData>
     */
    @Override
    public List<SaleData> getAll(SaleDataQueryVO saleDataQueryVO){
        QueryWrapper<SaleData> queryWrapper = WrapperUtils.queryWrapperByQueryVONoTime(saleDataQueryVO);
        if(saleDataQueryVO.getBefore()!=null){
            queryWrapper.ge("date",saleDataQueryVO.getBefore());
        }
        if(saleDataQueryVO.getAfter()!=null){
            queryWrapper.le("date",saleDataQueryVO.getAfter());
        }
        return saleDataMapper.selectList(queryWrapper);
    }

    /**
     * 通过id删除
     * @param id：saleDataId
     * @return Result<Object>
     */
    @Override
    public Result<Object> deleteById(String id){
        SaleData saleData=saleDataMapper.selectById(id);
        if(saleData==null){
            return Result.error(ResponseState.TARGET_NOT_EXIST.getValue(), ResponseState.TARGET_NOT_EXIST.getMessage());
        }
        saleDataMapper.deleteById(id);
        return Result.OK();
    }

    /**
    * 批量删除
    * @param ids：id列表
    * @return Result<Object>
    */
    @Override
    public Result<Object> batchDelete(List<String> ids){
        UpdateWrapper<SaleData> updateWrapper=new UpdateWrapper<>();
        updateWrapper.in("id",ids);
        saleDataMapper.delete(updateWrapper);
        return Result.OK();
    }

    /**
     * 下单
     * @param order
     */
//    @Async
    @Override
    public void addOrder(Order order) {
        System.out.println("下单了。。。");
        boolean isFirst=false;
        try {
            Timestamp today= DateUtils.getTodayTimestamp();
            SaleData saleData=saleDataMapper.selectOne(WrapperUtils.getQueryWrapper("date",today));
            if(saleData==null){
                saleData=new SaleData();
                saleData.setDate(today);
                isFirst=true;
            }
            saleData.setOrderNum(saleData.getOrderNum()+1);
            saleData.setOrderSale(saleData.getOrderSale()+order.getGoodsPrice());
            System.out.println(order.getGoods());
            JSONArray jsonArray=JSONArray.parseArray(order.getGoods());
            List<Cart> cartList=jsonArray.toJavaList(Cart.class);
            cartList.forEach(System.out::println);
            for(Cart cart:cartList){
                saleData.setGoodsNum(saleData.getGoodsNum()+cart.getNumber());
            }
            if(isFirst){
                saleDataMapper.insert(saleData);
            }else {
                saleDataMapper.updateById(saleData);
            }
            goodDataService.addOrder(order);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 退款
     * @param order
     */
    @Async
    @Override
    public void refund(Order order) {
        Timestamp date=DateUtils.getDate(order.getCreateAt());
        SaleData saleData=saleDataMapper.selectOne(WrapperUtils.getQueryWrapper("date",date));
        JSONArray jsonArray=JSONArray.parseArray(order.getGoods());
        List<Cart> cartList=jsonArray.toJavaList(Cart.class);
        for(Cart cart:cartList){
            saleData.setRefundGoodsNum(saleData.getRefundGoodsNum()+cart.getNumber());
        }
        saleData.setRefundRate(saleData.getRefundGoodsNum()/(double)saleData.getGoodsNum());
        saleDataMapper.updateById(saleData);
    }

    /**
     * 发货
     * @param order
     */
    @Async
    @Override
    public void delivery(Order order) {
        Timestamp date=DateUtils.getDate(order.getCreateAt());
        SaleData saleData=saleDataMapper.selectOne(WrapperUtils.getQueryWrapper("date",date));
        JSONArray jsonArray=JSONArray.parseArray(order.getGoods());
        List<Cart> cartList=jsonArray.toJavaList(Cart.class);
        for(Cart cart:cartList){
            saleData.setDeliverGoodsNum(saleData.getDeliverGoodsNum()+cart.getNumber());
        }
        saleData.setDeliverOrderNum(saleData.getDeliverOrderNum()+1);
        saleData.setDeliverSale(saleData.getDeliverSale()+order.getGoodsPrice());
        saleDataMapper.updateById(saleData);

    }

    /**
     * 访问页面
     * @param ipAddress
     */
    @Async
    @Override
    public void visitPage(IpAddress ipAddress) {
        boolean isFirst=false;
        Timestamp today= null;
        try {
            today = DateUtils.getTodayTimestamp();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SaleData saleData=saleDataMapper.selectOne(WrapperUtils.getQueryWrapper("date",today));
        if(saleData==null){
            saleData=new SaleData();
            saleData.setDate(today);
            isFirst=true;
        }
        saleData.setPageViews(saleData.getPageViews()+1);
        if(isFirst){
            saleDataMapper.insert(saleData);
        }else {
            saleDataMapper.updateById(saleData);
        }
    }

    /**
     * 访问商品详情页
     */
    @Async
    @Override
    public void visit() {
        boolean isFirst=true;
        Timestamp today= null;
        try {
            today = DateUtils.getTodayTimestamp();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SaleData saleData=saleDataMapper.selectOne(WrapperUtils.getQueryWrapper("date",today));
        if(saleData==null){
            saleData=new SaleData();
            saleData.setDate(today);
            isFirst=false;
        }
        saleData.setPageViews(saleData.getVisitNum()+1);
        saleData.setConvertRate(saleData.getDeliverGoodsNum()/(double)saleData.getVisitNum());
        if(isFirst){
            saleDataMapper.insert(saleData);
        }else {
            saleDataMapper.updateById(saleData);
        }
    }
}